import { auth, getVhopConfig, closeVhopRoom } from '@/apis/ttsa'
import { useTtsaStore } from '@/store/ttsa'
import { useUserStore } from '@/store/user'
import { useNetworkStore } from '@/store/network'
import { useTrack } from '@/hooks'
import Socket from '@/libs/socket'

export const useInit = async () => {
  const ttsaStore = useTtsaStore()
  const { online, tag, refresh_intention, userId, appId } = useUserStore()
  const vhopConfig = await getVhopConfig()
  const { digital_name: username, digital_secret_id: role_id, vhop_app_id: app_id, vhop_app_secret: app_secret, server_url: server } = vhopConfig
  // ttsa sdk文档链接 https://docs.qq.com/doc/DV1NTT0NlWW9hUVls
  const ttsa = new (window as LooseObject).XmovTTSA({
    container: '#ttsa',
    server,
    account: { username: `${username}_${Date.now()}`, role_id, app_id, app_secret },
    widgetCallback: ttsaStore.uicallback,
    rtcAggReportConfig: {
      // 采样
      sampleDensity: 600,
      sampleLength: 45,
      framesDroppedTolerant: 8
    },
    packetsLostRateCallback: () => {
      const network = useNetworkStore()
      network.check()
    },
    onRoomClosed: () => {
      console.log('TTSA close room')
      ttsaStore.error('链接异常，请重新链接', true)
      closeCallback(ttsa)
    },
    onstatechange: (state, type) => {
      console.log(`iceStateCallback: ${state} ${type}`)
      if (!['disconnected', 'failed'].includes(state)) return
      if (window._online === false || document.visibilityState === 'hidden') {
        ttsaStore.reconnecStatus = 'start'
      } else if (ttsaStore.hasController) {
        ttsaStore.reconnect()
      }
    },
    socketCallback: (state) => {
      console.log(`socketCallback: ${state}`)
      if (state !== 'disconnect') return
      if (window._online === false || document.visibilityState === 'hidden') {
        ttsaStore.error('您的网络环境出现异常，请检查网络后重新连接')
      } else if (ttsa.hasController) {
        ttsaStore.reconnect()
      }
    },
    support_ack: true,
    config: {
      offline: !online,
      auto_action: false,
      nlp: false,
      fps: 24,
      max_bitrate: ttsaStore.bitrate,
      tag,
      refresh_intention,
      app_id: appId,
      customer_user_id: userId
    },
    videoOptions: {
      autoplay: false,
      muted: false,
      showMutedButton: false,
    }
  })
  return ttsa
}

const setAuthSDK = (ttsa) => {
  const {
    token: { expire_in, expire_time, key, session_id, user_id: vhop_user_id },
    room: { room_id, ttsa_session_id },
    options: {
      account: { app_secret: secret_id, username: user_name },
    },
  } = ttsa
  return auth({
    user_name,
    expire_in,
    expire_time,
    key,
    session_id,
    vhop_user_id,
    room_id,
    ttsa_session_id,
    secret_id,
  })
}

const setSocket = () => {
  const userStore = useUserStore()
  const { appId, userId } = userStore
  const { setTrack } = useTrack()
  return new Socket(`${import.meta.env.XMOV_APP_SOCKET_URL}/h5/update_ttsasession_status/?app_id=${appId}&customer_user_id=${userId}`, {
    onMessage: ({ data = '' }) => {
      userStore.sessionId = data
      setTrack({ name: 'session_start' })
    }
  })
}

export const useStart = (ttsa) => {
  return ttsa.setup().then(async () => {
    await setAuthSDK(ttsa)
    ttsa._YL_SOCKET = setSocket()
    return Promise.resolve()
  })
}

export const useReconnect = (ttsa) => {
  if (ttsa._YL_SOCKET) {
    ttsa._YL_SOCKET.destroy()
    ttsa._YL_SOCKET = null
  }
  return ttsa.reconnect().then(async () => {
    await setAuthSDK(ttsa)
    ttsa._YL_SOCKET = setSocket()
    return Promise.resolve()
  })
}

const closeCallback = (ttsa) => {
  const key = (window as LooseObject)?.XmovTTSA?.NODES?._STORAGE_KEY_ROOM_HISTORY_ ?? 'xmov_ttsa_history_room'
  const cfg = localStorage.getItem(key)
  if (cfg) {
    const { key, role_id: secret_id, room_id, username: user_name } = JSON.parse(cfg)
    if (!(secret_id && room_id && user_name)) return Promise.resolve()
    return closeVhopRoom({ key, secret_id, room_id, user_name })
  }
  ttsa._YL_SOCKET.destroy()
}

export const useLog = (msg = '', ...params) => {
  window.console.log(
    `%c::TTSA:%c${msg}%c${new Date().toLocaleString()}`,
    'background: #35495e;padding: 2px 3px;border-radius: 3px 0 0 3px;color: #fff;font-weight: bold;',
    'background: #41b883 ;padding: 2px 3px;color: #181e85;font-weight: bold;',
    'background: #aaa ;padding: 2px 3px;border-radius: 0 3px 3px 0;color: #fff;font-weight: bold;',
  )
  window.console.log(...params)
}
